<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item prop="userId">
      <el-input v-model="loginForm.userId" placeholder="请输入工号/用户名/手机号">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="name" v-if="loginSwatch">
      <el-input v-model="loginForm.name" placeholder="请输入名称">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" show-password autocomplete="new-password">
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="verifyPassword" v-if="loginSwatch">
      <el-input
        v-model="loginForm.verifyPassword"
        type="password"
        placeholder="请再次确认密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item class="register" style="margin-bottom: 10px">
      <el-link :underline="false" @click="goRegister">{{ loginSwatch ? "已有账号？去登录" : "没有账号？去注册" }}</el-link>
    </el-form-item>
    <!-- <el-form-item prop="code">
      <el-input v-model="loginForm.code" placeholder="验证码" style="width: 60%">
        <template #prefix>
          <el-icon class="el-input__icon">
            <img style="width: 100%; height: 100%" src="/src/assets/icons/validCode.svg" />
          </el-icon>
        </template>
      </el-input>
      <div class="login-code">
        <img :src="codeUrl" @click="getCodeHandler" class="login-code-img" />
      </div>
    </el-form-item> -->
  </el-form>
  <div class="login-btn">
    <el-button
      :icon="UserFilled"
      size="large"
      type="primary"
      :loading="loading"
      @click="loginHandler(loginFormRef)"
      style="width: 100%"
    >
      {{ loginSwatch ? "注册" : "登录" }}
    </el-button>
  </div>
</template>

<script setup lang="ts">
import type { LoginForm } from "@/typings";
import type { FormRules, FormInstance } from "element-plus";
import { ElMessage, ElNotification } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { User, UserFilled } from "@element-plus/icons-vue";
import { useKeepAliveStore, useTabsStore, useUserStore } from "@/stores";
import { login, register } from "@/api";
import { HOME_URL, SALUTATION } from "@/config";
import { useRouter } from "vue-router";
import { getTimeState, random } from "@/utils";
import md5 from "md5";
import { phoneVerify } from "@/utils/formVerify";

const props = defineProps<{
  setTitle: (val: string) => void;
}>();
const loginSwatch = ref<boolean>(false);
const loginFormRef = ref<FormInstance>();
const loading = ref(false);
const router = useRouter();
const useUser = useUserStore();
const useTabs = useTabsStore();
const useKeepAlive = useKeepAliveStore();
const loginForm: LoginForm = reactive({
  userId: "",
  name: "",
  password: "",
  verifyPassword: ""
});

const validator = (_: any, value: string, callback: (error?: string | Error) => void) => {
  if (loginSwatch.value && loginForm.password !== value) {
    callback(new Error("两次密码输入不一致"));
  } else {
    callback();
  }
};

const loginRules: FormRules<typeof loginForm> = reactive({
  userId: [
    { required: true, message: "用户名称不能为空!", trigger: "blur" },
    { min: 4, max: 16, message: "长度为 4 ~ 16 位!", trigger: "blur" },
    { validator: phoneVerify, trigger: "blur" }
  ],
  name: [{ min: 2, max: 10, message: "长度为 2 ~ 10 位!", trigger: "blur" }],
  password: [
    { required: true, message: "用户密码不能为空!", trigger: "blur" },
    { min: 6, max: 16, message: "密码的长度为 6 ~ 16 位!", trigger: "blur" }
  ],
  verifyPassword: [
    { required: true, message: "确认密码不能为空!", trigger: "blur" },
    { validator: validator, trigger: "blur" }
  ]
  // code: [{ required: true, message: "验证码不能为空!", trigger: "blur" }]
});

/**
 * @description 登录处理
 * @param formEl 表单实例
 */
const loginHandler = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid: boolean) => {
    if (!valid) return;
    if (!loginSwatch.value) {
      loading.value = true;
      const params = {
        phoneNumber: loginForm.userId,
        passWord: md5(loginForm.password!)
      };
      try {
        const loginResult = await login(params);
        if (loginResult.code === 200) {
          // ElMessage.success("登录成功");
          const { data } = loginResult;
          useUser.token = data.access_token;
          useUser.userInfo = data;
          // await initDynamicRouter();
          useTabs.closeMultipleTab();
          useKeepAlive.setKeepAliveName();
          router.push(HOME_URL);
          ElNotification({
            title: "哈喽，" + useUser.userInfo.userName + getTimeState(),
            message: SALUTATION[random(0, SALUTATION.length - 1)],
            type: "success",
            duration: 5000
          });
          return;
        }
        // todo 判断验证码错误的时候从新刷新验证码
        ElMessage.error(loginResult.message);
      } catch (error) {
        ElMessage.error("登录失败，请稍后再试!");
      } finally {
        loading.value = false;
      }
    }
    if (loginSwatch.value) {
      loading.value = true;
      const params = {
        phoneNumber: loginForm.userId,
        userName: loginForm.name,
        passWord: md5(loginForm.password!)
      };
      try {
        const result = await register(params);
        if (result.code === 200) {
          ElMessage.success("注册成功");
          loginSwatch.value = !loginSwatch.value;
          props.setTitle(loginSwatch.value ? "注册" : "登录");
        }
      } catch (error) {
        ElMessage.error("注册失败，请稍后再试!");
      } finally {
        loading.value = false;
      }
    }
  });
};

// 注册切换
const goRegister = () => {
  loginFormRef.value && loginFormRef.value.clearValidate();
  loginSwatch.value = !loginSwatch.value;
  props.setTitle(loginSwatch.value ? "注册" : "登录");
};

onMounted(async () => {
  // await getCodeHandler();
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      loginHandler(loginFormRef.value);
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";

.login-code {
  width: 40%;
  height: 38px;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-code-img {
    cursor: pointer;
    height: 100%;
    vertical-align: middle;
  }
}
.register {
  :deep(.el-form-item__content) {
    justify-content: flex-end;
  }
}
</style>
